package com.hongshan.wallet.util

import android.app.AppOpsManager
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.media.MediaPlayer
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.provider.Settings.ACTION_APP_NOTIFICATION_SETTINGS
import android.provider.Settings.EXTRA_APP_PACKAGE
import android.support.annotation.RawRes
import android.support.annotation.RequiresApi
import android.support.v4.app.NotificationCompat
import com.hongshan.wallet.BuildConfig
import com.hongshan.wallet.MyApplication
import com.hongshan.wallet.R


/**
 * Copyright Zhangxx.
 * Copyright (c) 2019
 * All rights reserved
 *
 * @project  : Wallet
 * @package  : com.example.wallet.util
 * @author   : zhangxx
 * @date     : 2019/4/17
 * @email    : qq957413212@hotmail.com
 * @desc     : //TODO
 */

object NotificationUtils {

    val manager by lazy { MyApplication.applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager }

    @RequiresApi(Build.VERSION_CODES.O)
    fun createNotificationChannel(voice: Int?) {
        val channel = NotificationChannel(id, name, NotificationManager.IMPORTANCE_HIGH)
        if (voice != null) {
            channel.setSound(
                Uri.parse("android.resource://${BuildConfig.APPLICATION_ID}/$voice"),
                Notification.AUDIO_ATTRIBUTES_DEFAULT
            )
        } else{
            channel.setSound(null, Notification.AUDIO_ATTRIBUTES_DEFAULT)
        }
        manager.createNotificationChannel(channel)
    }


    fun getNotification_28(title: String, content: String, autoCancle: Boolean): NotificationCompat.Builder {
        return NotificationCompat.Builder(MyApplication.applicationContext, id)
            .setContentTitle(title)
            .setContentText(content)
            .setOnlyAlertOnce(true)
            .setSmallIcon(android.R.drawable.stat_notify_more)
            .setAutoCancel(autoCancle)
    }

    fun getNotification_25(title: String, content: String, autoCancle: Boolean): NotificationCompat.Builder {
        return NotificationCompat.Builder(MyApplication.applicationContext)
            .setContentTitle(title)
            .setContentText(content)
            .setOnlyAlertOnce(true)
            .setSmallIcon(android.R.drawable.stat_notify_more)
            .setAutoCancel(autoCancle)
    }

    fun sendNotification(title: String, content: String, intent: PendingIntent?, @RawRes voice: Int? = null) {
        val notification = if (Build.VERSION.SDK_INT >= 26) {
            createNotificationChannel(voice)
            getNotification_28(title, content, true).setContentIntent(intent).build()
        } else {
            getNotification_25(title, content, true).setContentIntent(intent).build()
        }
        if (voice != null && Build.VERSION.SDK_INT < 26) {
            notification.sound =
                Uri.parse("android.resource://${BuildConfig.APPLICATION_ID}/voice")
        }
        val player = MediaPlayer.create(MyApplication.applicationContext, R.raw.new_order)
        player.start()
        notification.sound = null
        manager.notify(1, notification)
    }

    private val CHECK_OP_NO_THROW = "checkOpNoThrow"
    private val OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION"

    fun isNotificationEnabled(context: Context): Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            ///< 8.0手机以上
            if ((context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).importance == NotificationManager.IMPORTANCE_NONE) {
                return false
            }
        }

        val mAppOps = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            context.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager
        } else {
            return true
        }
        val appInfo = context.applicationInfo
        val pkg = context.applicationContext.packageName
        val uid = appInfo.uid

        val appOpsClass: Class<*>?
        try {
            appOpsClass = Class.forName(AppOpsManager::class.java.name)
            val checkOpNoThrowMethod = appOpsClass!!.getMethod(
                CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE,
                String::class.java
            )
            val opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION)

            val value = opPostNotificationValue.get(Int::class.java) as Int
            return checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) as Int == AppOpsManager.MODE_ALLOWED
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return false
    }

    /**
     * 通知权限申请
     * @param context
     */
    fun requestNotify(context: Context) {
        try {
            val localIntent = Intent()
            ///< 直接跳转到应用通知设置的代码
            when {
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> {
                    localIntent.action = ACTION_APP_NOTIFICATION_SETTINGS
                    localIntent.putExtra(EXTRA_APP_PACKAGE, context.packageName)
                }
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Build.VERSION.SDK_INT < Build.VERSION_CODES.O -> {
                    localIntent.action = "android.settings.APP_NOTIFICATION_SETTINGS"
                    localIntent.putExtra("app_package", context.packageName)
                    localIntent.putExtra("app_uid", context.applicationInfo.uid)
                }
                Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT -> {
                    localIntent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                    localIntent.addCategory(Intent.CATEGORY_DEFAULT)
                    localIntent.data = Uri.parse("package:" + context.packageName)
                }
                "MI 6" == Build.MODEL ->{
                    localIntent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                    val uri = Uri.fromParts("package", BuildConfig.APPLICATION_ID, null)
                    localIntent.data = uri;

                }
            }
            context.startActivity(localIntent)
        } catch (e: Exception) {
            e.printStackTrace()
            val localIntent = Intent()
            localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            localIntent.action = "android.settings.APPLICATION_DETAILS_SETTINGS"
            localIntent.data = Uri.fromParts("package", context.packageName, null)
            context.startActivity(localIntent)
        }
    }

    val id = "trading_alert"
    val name = "交易提醒"
}